#include <iostream>

void pointerUsage();
void pointerUsage2();
void pointerUsage3();
void pointerUsage4();
void pointerUsage5();
void pointerUsage6();

int main(int argc, char *argv[]) {
  std::cout << "==== ch03 p01 ====" << std::endl;
  printf("---- pointerUsage() ----\n");
  pointerUsage();
  printf("---- pointerUsage2() ----\n");
  pointerUsage2();
  printf("---- pointerUsage3() ----\n");
  pointerUsage3();
  printf("---- pointerUsage4() ----\n");
  pointerUsage4();
  printf("---- pointerUsage5() ----\n");
  pointerUsage5();
  printf("---- pointerUsage6() ----\n");
  pointerUsage6();
  return 0;
}

void pointerUsage() {
  int a{10};
  // int *myPtr = &a;
  int *myPtr{&a};
  printf("myPtr is %p; value is %d;\n", myPtr, *myPtr);
}

void pointerUsage2() {
  int a{10};
  int *aPtr{&a};
  // 解引用后, 就可以当成普通变量使用了.
  // 可以赋值
  *aPtr = 20;
  // 可以取值
  printf("a = %d\n", *aPtr);
}

class Time {
  int year_{2024};

public:
  int getYear() const { return year_; }
};

void pointerUsage3() {
  Time t;
  Time *pt{&t};
  printf("year is %d\n", pt->getYear());
}

struct Person {
  char name[100];
};

void printName(Person *p) { printf("name is %s\n", p->name); }

void pointerUsage4() {
  Person ps[]{{"Alice"}, {"Bob"}};
  printName(ps);
}

void printName(Person *p, size_t num) {
  for (size_t i = 0; i < num; ++i) {
    printf("name is %s\n", p[i].name);
  }
}

void pointerUsage5() {
  Person ps[]{{"Alice"}, {"Bob"}};
  printName(ps, sizeof(ps) / sizeof(Person));
}

void pointerUsage6() {
  int a[]{1, 2, 3};
  int *pa2_1 = &a[2]; // 指向 a[2]
  int *pa2_2 = a + 2; // 指向 a[2], 指针从数组首地址移动 2*4=8 字节
  printf("方式1: a[2] = %d; 方式2: a[2] = %d\n", *pa2_1, *pa2_2);
}
